package com.qf.dao.impl;

import com.qf.dao.UserDao;
import com.qf.entity.User;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * --- 天道酬勤 ---
 *
 * @author QiuShiju
 * @date 2024/6/26
 * @desc
 */
public class UserDaoImpl implements UserDao {
    @Override
    public User login(String username, String password) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/java2403?useSSL=false&characterEncoding=utf-8", "root", "123456");
            String sql = "select * from tb_user where username = ? and password = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);

            rs = ps.executeQuery( );
            while (rs.next()){
                user = new User(  );
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setCreateTime(rs.getDate("create_time"));
                user.setMoney(rs.getDouble("money"));
                user.setSex(rs.getInt("sex"));
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                rs.close( );
                ps.close( );
                conn.close( );
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        return user;
    }

    @Override
    public boolean regist(User user) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/java2403?useSSL=false&characterEncoding=utf-8", "root", "123456");
            String sql = "insert into tb_user (username,password,phone,create_time,money,sex) " +
                    " values (?,?,?,?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getPhone());
            ps.setDate(4,new java.sql.Date(user.getCreateTime().getTime()));
            ps.setDouble(5,user.getMoney());
            ps.setInt(6,user.getSex());

            int i = ps.executeUpdate( );
            return i > 0 ? true : false;
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                ps.close( );
                conn.close( );
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
